/**
 * 
 */
package com.alstudio.module.recharge;

import java.net.HttpURLConnection;
import java.net.URLEncoder;

import org.apache.http.Header;

import android.text.TextUtils;

import com.alstudio.app.ALLocalEnv;
import com.alstudio.pojo.module.server.Serverlet;
import com.alstudio.utils.log.ALLog;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

/**
 * 提交订单工具类
 * 
 * @author alonso lee
 * 
 */
public class RechargeHttpReqUtils {

	/**
	 * 提交订单回调方法
	 * 
	 * @author alonso lee
	 * 
	 */
	public interface CommitRechargOrderCallback {
		public void onSuccess(ComintChargeOrderHttpResultWrap result);

		public void onFailure(int statusCode, Throwable error);
	}

	/**
	 * 请求提交易宝充值订单
	 * 
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public static void requestUploadYeepayOrder(final ChargeHttpRqWrap data,
			final CommitRechargOrderCallback callback) {

		if (TextUtils.isEmpty(data.getToken())
				|| TextUtils.isEmpty(data.getProductId())
				|| TextUtils.isEmpty(data.getOrderId())
				|| TextUtils.isEmpty(data.getUsername())) {
			throw new IllegalArgumentException();
		}

		try {

			String user = data.getUsername();
			if (user.contains("@")) {
				user = user.substring(0, user.indexOf("@"));
			}

			String params = String
					.format("?username=%s&token=%s&type=%s&orderid=%s&productid=%s&downfrom=%s",
							URLEncoder.encode(user, "UTF-8"), URLEncoder
									.encode(data.getToken(), "UTF-8"),
							URLEncoder.encode("createorder"), URLEncoder
									.encode(data.getOrderId()), URLEncoder
									.encode(data.getProductId()), URLEncoder
									.encode(ALLocalEnv.getLocalEnv()
											.getDownloadUrl()));

			String baseUrl = null;
			if ((ALLocalEnv.getLocalEnv().getVersionConfig().getServerInfo() == null)
					|| TextUtils.isEmpty(ALLocalEnv.getLocalEnv()
							.getVersionConfig().getServerInfo()
							.getChargeCallbackUrl())) {
				baseUrl = Serverlet.YEE_PAY_SERVERLET_URL;
			} else {
				baseUrl = ALLocalEnv.getLocalEnv().getVersionConfig()
						.getServerInfo().getChargeCallbackUrl();
			}

			String url = baseUrl + params;
			ALLog.d("请求上传医保充值订单" + url);

			// 设置请求属性

			AsyncHttpClient client = new AsyncHttpClient();
			client.addHeader("keepAlive", "false");
			client.addHeader("content-type", "application/octet-stream");
			client.addHeader("Connection", "close");
			client.addHeader("token", data.getToken());
			client.post(url, new AsyncHttpResponseHandler() {

				@Override
				public void onSuccess(int statusCode, Header[] headers,
						byte[] responseBody) {
					// TODO Auto-generated method stub
					ALLog.d("提交成功");

					if (headers != null) {
						ComintChargeOrderHttpResultWrap result = new ComintChargeOrderHttpResultWrap();
						for (Header h : headers) {
							ALLog.d("名字 " + h.getName() + " 值 " + h.getValue());
						}
						if (callback != null) {
							result.setRechargeType(data.getRechargeType());
							callback.onSuccess(result);
						}
					}

				}

				@Override
				public void onFailure(int statusCode, Header[] headers,
						byte[] responseBody, Throwable error) {
					// TODO Auto-generated method stub
					ALLog.d("提交失败");
					if (headers != null) {
						for (Header h : headers) {
							ALLog.d("名字 " + h.getName() + " 值 " + h.getValue());
						}
					}

					if (callback != null) {
						callback.onFailure(statusCode, error);
					}

				}
			});

		} catch (Exception e) {
			e.printStackTrace();
			if (callback != null) {
				callback.onFailure(-1, e);
			}
		} finally {
		}

	}

	/**
	 * 请求提交支付宝充值订单
	 * 
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public static ComintChargeOrderHttpResultWrap requestUploadAlipayOrder(
			final ChargeHttpRqWrap data, final CommitRechargOrderCallback callback) {
		if (TextUtils.isEmpty(data.getToken())
				|| TextUtils.isEmpty(data.getProductId())
				|| TextUtils.isEmpty(data.getOrderId())
				|| TextUtils.isEmpty(data.getUsername())) {
			throw new IllegalArgumentException();
		}

		ComintChargeOrderHttpResultWrap result = new ComintChargeOrderHttpResultWrap();
		HttpURLConnection con = null;

		try {

			String user = data.getUsername();
			if (user.contains("@")) {
				user = user.substring(0, user.indexOf("@"));
			}

			String params = String
					.format("?username=%s&token=%s&type=%s&orderid=%s&productid=%s&downfrom=%s",
							URLEncoder.encode(user, "UTF-8"), URLEncoder
									.encode(data.getToken(), "UTF-8"),
							URLEncoder.encode("createorder"), URLEncoder
									.encode(data.getOrderId()), URLEncoder
									.encode(data.getProductId()), URLEncoder
									.encode(ALLocalEnv.getLocalEnv()
											.getDownloadUrl()));

			String baseUrl = null;
			if ((ALLocalEnv.getLocalEnv().getVersionConfig().getServerInfo() == null)
					|| TextUtils.isEmpty(ALLocalEnv.getLocalEnv()
							.getVersionConfig().getServerInfo().getAlipayUrl())) {
				baseUrl = Serverlet.ALIPAY_SERVERLET_URL;
			} else {
				baseUrl = ALLocalEnv.getLocalEnv().getVersionConfig()
						.getServerInfo().getAlipayUrl();
			}

			String url = baseUrl + params;
			ALLog.d("请求上传致富饱充值订单" + url);

			AsyncHttpClient client = new AsyncHttpClient();
			client.addHeader("keepAlive", "false");
			client.addHeader("content-type", "application/octet-stream");
			client.addHeader("Connection", "close");
			client.addHeader("token", data.getToken());
			client.post(url, new AsyncHttpResponseHandler() {

				@Override
				public void onSuccess(int statusCode, Header[] headers,
						byte[] responseBody) {
					// TODO Auto-generated method stub
					ALLog.d("提交成功");

					if (headers != null) {
						ComintChargeOrderHttpResultWrap result = new ComintChargeOrderHttpResultWrap();
						for (Header h : headers) {
							ALLog.d("名字 " + h.getName() + " 值 " + h.getValue());
						}
						if (callback != null) {
							result.setRechargeType(data.getRechargeType());
							callback.onSuccess(result);
						}
					}

				}

				@Override
				public void onFailure(int statusCode, Header[] headers,
						byte[] responseBody, Throwable error) {
					// TODO Auto-generated method stub
					ALLog.d("提交失败");
					if (headers != null) {
						for (Header h : headers) {
							ALLog.d("名字 " + h.getName() + " 值 " + h.getValue());
						}
					}

					if (callback != null) {
						callback.onFailure(statusCode, error);
					}

				}
			});

		} catch (Exception e) {
			e.printStackTrace();
			if (callback != null) {
				callback.onFailure(-1, e);
			}
		} finally {
			if (con != null)
				con.disconnect();
		}

		return result;

	}

}
